package com.studyjun.filmsimple;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

/**
 * 进度条
 * 
 * @author studyjun
 * 
 */
public class Progress extends View {

	private float top;
	private float right;
	private float buttom;
	private float left;

	public Progress(Context context) {
		super(context);
	}

	public Progress(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public Progress(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private void init() {
//		ViewTreeObserver vto = this.getViewTreeObserver();
//		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
//
//			@Override
//			public void onGlobalLayout() {
//				Progress.this.getViewTreeObserver()
//						.removeGlobalOnLayoutListener(this);
//
//				right = Progress.this.getMeasuredWidth();
//				buttom = Progress.this.getMeasuredHeight();
//			}
//		});
		
		left=0;
		top=0;
		right = getWidth();
		buttom =getHeight();
	}
	
	private int color = Color.GREEN;
	private Thread thread;
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		Paint paint = new Paint(); //新建画笔
		paint.setAntiAlias(true); //消除锯齿
		paint.setColor(color); 
		RectF r = new RectF(left, top, right, buttom); //设置矩形框大小
		canvas.drawRect(r, paint);//填充矩形框

	}
	
	/**
	 * 进度条滚动
	 */
	public void start(final boolean isRun) {
		if (isRun==false) { //抬起手指全部变成0返回。
			left=0;
			top=0;
			right =0;
			buttom =0;
			return;
		}
		init(); //初始化
		new Thread() {
			public void run() {
				int time = 6000; // 6000ms
				float section = right/200f; //绘画100次，每次减少固定值
				while (isRun && time > 0) {
					left+=section;
					right-=section;
					try {
						sleep(60);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					time -= 60;
					postInvalidate(); //重画
				}
				
			}

		}.start();
	}
	
	
	/**
	 * 取消，颜色变成红色
	 * @param cancel
	 */
	public void cancel(boolean cancel){
		if (cancel) {
			color =Color.RED;
		} else{
			color= Color.GREEN;
		}
	}
	
}
